package org.codingq92.basic.io.nio;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * NIO: FileChannel Api
 * 注意事项：Channel 只存在于子类中不存在与父类 所以不能InputStream fis = new FileInputStream()、OutputStream fos = new FileOutputStream()
 *
 * @author CodingQ92
 * @date 2025/06/29 08:15
 */
public class FileChannelApi {
    public static void main(String[] args) {
//        write();
        read();
    }

    private static void read() {
        try (FileInputStream fis = new FileInputStream("a.txt"); // 目标文件
             FileChannel fisChannel = fis.getChannel() // 目标文件的channel对象
        ) {
            // 缓冲buffer
            ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
            // 读取数据到缓冲区
            int read = fisChannel.read(byteBuffer);
            while (read != -1) {
                System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>: " + read);
                // 翻转缓冲
                byteBuffer.flip();
                if (byteBuffer.hasRemaining()) {
                    String s = new String(byteBuffer.array(), 0, byteBuffer.remaining());
                    System.out.println(s);
                }
                // 清空缓冲
                byteBuffer.clear();
                read = fisChannel.read(byteBuffer);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void write() {
        try (FileOutputStream fos = new FileOutputStream("a.txt"); // 目标文件
             FileChannel fosChannel = fos.getChannel() // 目标文件的channel对象
        ) {
            // 缓冲buffer
            ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
            byteBuffer.put("hello channel".getBytes());
            // 切换缓冲为写出模式
            byteBuffer = byteBuffer.flip();
            // 通过通道写数据到文件中
            int write = fosChannel.write(byteBuffer);
            System.out.println("write: " + write);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
